//
//  OfflineLocationFetchRequestModel.swift
//  LocationTrackerAdmin
//
//  Created by mac on 2025/4/17.
//

import Fluent
import Vapor
import FluentKit
import SQLKit
final class OfflineLocationFetchRequestModel: Model, Content {
    static let schema = "offline_location_fetch_request"
    
    @ID(custom: FieldKeys.id)
    var id: String?
    
    @Field(key: FieldKeys.requestUserID)
    var requestUserID: String
    
    @Field(key: FieldKeys.responseUserID)
    var responseUserID: String
    
    @Timestamp(key: FieldKeys.createdAt, on: .create)
    var createdAt: Date?
    
    @Field(key: FieldKeys.state)
    var state: Int
    
    init(id: String? = nil, requestUserID: String, responseUserID: String, createdAt: Date? = nil, state: Int) {
        self.id = id
        self.requestUserID = requestUserID
        self.responseUserID = responseUserID
        self.createdAt = createdAt
        self.state = state
    }
    
    init() {
        
    }
}

extension OfflineLocationFetchRequestModel {
    struct FieldKeys {
        static var id: FieldKey { "offline_location_fetch_request_id" }
        static var requestUserID: FieldKey { "offline_location_fetch_request_user_id" }
        static var responseUserID: FieldKey { "offline_location_fetch_request_response_user_id" }
        static var state: FieldKey { "offline_location_fetch_request_state" }
        static var createdAt: FieldKey { "offline_location_fetch_request_created_at" }
    }
}

struct OfflineLocationFetchRequestMigration: AsyncMigration {
    func prepare(on database: Database) async throws {
        try await database.schema(OfflineLocationFetchRequestModel.schema)
            .field(OfflineLocationFetchRequestModel.FieldKeys.id, .string, .required, .identifier(auto: false), .custom("COMMENT '记录ID'"))
            .field(OfflineLocationFetchRequestModel.FieldKeys.requestUserID, .string, .required, .custom("COMMENT '请求人的ID'"))
            .field(OfflineLocationFetchRequestModel.FieldKeys.responseUserID, .string, .required, .custom("COMMENT '响应人的ID'"))
            .field(OfflineLocationFetchRequestModel.FieldKeys.createdAt, .custom("datetime(0)"), .required, .sql(.default(SQLFunction("now"))), .custom("COMMENT '创建日期'"))
            .field(OfflineLocationFetchRequestModel.FieldKeys.state, .int, .required, .custom("COMMENT '请求是否响应，0：未响应，1：已响应'"))
            .create()
    }
    
    func revert(on database: Database) async throws {
        try await database.schema(OfflineLocationFetchRequestModel.schema).delete()
    }
}
